<template>
  <div class="app-container bg-white">
    <!-- 页面头部 -->
    <!-- 页面内容 -->
    <div class="page-body">
      <div class="flex space-between align-center">
        <el-form size="small" :inline="true">
          <el-form-item>
            <el-input size="small" placeholder="请输入供应商名称" v-model.trim="search.name" maxlength="50" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-input size="small" placeholder="请输入供应商编码" v-model.trim="search.suppStandard" clearable maxlength="10"></el-input>
          </el-form-item>
          <el-form-item>
          <el-input size="small" placeholder="请输入供应商代码" v-model="search.suppCode"></el-input>
        </el-form-item>
          <el-form-item>
            <el-date-picker size="small" v-model="search.times" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :value-format="'yyyy-MM-dd'"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button size="small" class="width_104" type="primary" @click="getPageDataList()">查询</el-button>
            <el-button size="small" class="width_104" @click="resetOption()">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button size="mini" type="success" icon="el-icon-document-add" @click="addSupplyOption()" v-if="roleBtns.includes('goods:goodsSupplier:add') || $store.getters.isAdmin">新建供应商</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteAllSupplyOption()" v-if="roleBtns.includes('goods:goodsSupplier:remove') || $store.getters.isAdmin">批量删除</el-button>
        <el-button size="mini" type="primary" icon="el-icon-download" @click="exportOption()" class="fr">批量导出</el-button>
      </div>
      <!-- 数据table -->
      <el-table class="margin_top_20" ref="multipleTableContent" :data="pageData" stripe :header-cell-style="tableHeaderStyle" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="42"></el-table-column>
        <el-table-column prop="name" label="供应商名称">
          <template slot-scope="scope">
            <div class="text-ellipsis_2" :title="scope.row.name">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="suppType" label="供应商类型">
          <template slot-scope="scope">
            <span v-if="scope.row.suppType == 0">内部</span>
            <span v-else>外部</span>
          </template>
        </el-table-column>
        <el-table-column prop="suppCode" label="供应商代码"></el-table-column>
        <el-table-column prop="suppStandard" label="供应商编码"></el-table-column>
        <el-table-column prop="auditStatus" label="审核状态">
        <template slot-scope="scope">
            <span v-if="scope.row.auditStatus == 0">未审核</span>
            <span v-else-if="scope.row.auditStatus == 1">审核中</span>
            <span v-else-if="scope.row.auditStatus == 2">通过</span>
            <span v-else>驳回</span>
          </template>
          </el-table-column>
        <el-table-column prop="creatorName" label="创建人"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="status" label="是否启用">
          <template slot-scope="scope">
            <el-switch :value="scope.row.status == 1?true:false" @change="switchChange($event, scope.row)" :disabled="(scope.row.auditStatus == 0 ||　scope.row.auditStatus == 1 || scope.row.auditStatus == 3)? true : false"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope" >
            <div v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 1">
            <button class="my-btn my-btn--mini my-btn--primary plain" @click="showSupplyOption(scope.row)" v-if="roleBtns.includes('goods:goodsSupplier:show') || $store.getters.isAdmin">查看</button>
            </div>
            <div v-else-if="scope.row.auditStatus == 2 && scope.row.status ">
            <button class="my-btn my-btn--mini my-btn--primary plain" @click="showSupplyOption(scope.row)" v-if="roleBtns.includes('goods:goodsSupplier:show') || $store.getters.isAdmin">查看</button>
            <button class="my-btn my-btn--mini my-btn--primary plain" @click="editSupplyOption(scope.row)" v-if="roleBtns.includes('goods:goodsSupplier:update') || $store.getters.isAdmin">编辑</button>
            <button class="my-btn my-btn--mini my-btn--danger plain" @click="deleteSupplyOption(scope.row.id)" v-if="roleBtns.includes('goods:goodsSupplier:remove') || $store.getters.isAdmin">删除</button>
          </div>
          <div v-else>
            <button class="my-btn my-btn--mini my-btn--primary plain" @click="showSupplyOption(scope.row)" v-if="roleBtns.includes('goods:goodsSupplier:show') || $store.getters.isAdmin">查看</button>
            <button class="my-btn my-btn--mini my-btn--primary plain" @click="editSupplyOption(scope.row)" v-if="roleBtns.includes('goods:goodsSupplier:update') || $store.getters.isAdmin">编辑</button>
            <el-popover placement="top-start" title="驳回原因" width="200" trigger="click" :content="scope.row.auditRemark">
              <button class="my-btn my-btn--mini my-btn--primary plain" style="margin-left:10px;margin-right: 10px" slot="reference">驳回原因</button>
            </el-popover>
            <!-- <button class="my-btn my-btn--mini my-btn--primary plain" @click="rejectSupplyOption(scope.row)" v-if="roleBtns.includes('goods:goodsSupplier:update') || $store.getters.isAdmin">驳回原因</button> -->
            <button class="my-btn my-btn--mini my-btn--danger plain" @click="deleteSupplyOption(scope.row.id)" v-if="roleBtns.includes('goods:goodsSupplier:remove') || $store.getters.isAdmin">删除</button>
          </div>
          </template>
          
        </el-table-column>
      </el-table>
    </div>

    <div class="text-center">
      <el-pagination background @size-change="handleSizeChange" @current-change="handlePagingChange" :current-page="pageIndex" :page-sizes="pageSizes" :page-size="pageSize" :layout="paginationLayout" :total="pageCount"> </el-pagination>
    </div>

    <el-dialog :title="title + '供应商'" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="isShowDialog">
      <el-form :model="supplyForm" ref="supplyFormRef" label-width="150px" :disabled="isShowerMode">
        <el-form-item label="供应商名称" prop="name" :rules="rules.name">
          <el-input class="input_item" v-model.trim="supplyForm.name" placeholder="请输入供应商名称" @input="watchInput($event, 'name')" maxlength="50" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="供应商类型" prop="suppType">
          <el-radio-group v-model="supplyForm.suppType" @change="changeType">
            <el-radio :label="0">内部</el-radio>
            <el-radio :label="1">外部</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="供应商代码" prop="suppCode" v-if="supplyForm.suppType == 0">
            <el-input class="input_item" v-model.trim="supplyForm.suppCode" placeholder="请输入供应商代码" maxlength="10" @keydown.native="inputUnpass"></el-input>
        </el-form-item> -->
        <el-form-item label="供应商编码" required>
          <el-input class="input_item" v-model.trim="supplyForm.suppStandard" placeholder="请输入供应商编码" maxlength="10" @input="inputSuppCode" show-word-limit :disabled="supplyForm.suppType == 1"></el-input>
          <span class="text-gray">(请输入数字或大写字母)</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelSubmit()">取 消</el-button>
        <el-button type="primary" @click="confirmSubmit()" :loading="submitLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Setting from '@/settings'
import { mapGetters } from 'vuex'
import { GetStoreSupplyListByParams, SaveStoreSupply, GetStoreSupplyOneItem, UpdateStoreSupply, RemoveStoreSupply, ChangeStoreSupplyStatus, GetInRandomCode } from '@/views/store-management/services/index'

export default {
  name: 'StoreSupply',
  data() {
    return {
      // 查询条件
      search: {
        name: '',
        suppStandard: '',
        suppCode: '',
        times: [],
      },
      pageIndex: 1,
      pageSize: Setting.defaultTablePaginationSize,
      pageSizes: Setting.tablePaginationSizes,
      tableHeaderStyle: Setting.tableHeaderStyle,
      paginationLayout: Setting.tablePaginationLayout,
      pageData: [],
      pageCount: 0,
      loading: false,

      editSupplyId: '',
      isShowDialog: false,
      isEditorMode: false,
      isShowerMode: false,
      supplyForm: {
        name: '',
        suppStandard: '',
        suppType: '0',
      },
      submitLoading: false,
      multipleSelection: [],
      rules: {
        name: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
        // suppStandard: [{ required: true, message: '请输入供应商编码', trigger: 'blur' }],
      },
    }
  },
  computed: {
    title() {
      return this.isShowerMode ? '查看' : this.isEditorMode ? '编辑' : '新建' 
    },
    ...mapGetters(['roleBtns']),
  },
  methods: {
    //驳回原因弹出框
    rejectSupplyOption(data) {
        this.$alert('这是一段内容', '驳回原因', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'info',
              message: `action: ${ action }`
            });
          }
        });
      },
    inputSuppCode(val) {
      val = val.replace(/[^\w\.\/]/ig, '')
      this.supplyForm.suppStandard = val.toUpperCase();
    },
    // console.log(val)
    //   if(this.isEditorMode) {
    //      if(val == 1) {
    //       this.getCode();

    //       this.supplyForm.suppStandard = localStorage.getItem('code')
    //       this.$forceUpdate()
    //   }else {
    //     this.supplyForm.suppStandard = ''
    //   }
    //   }else {
    //     if(val == 1) {
    //       this.getCode();

    //       this.supplyForm.suppStandard = localStorage.getItem('code')
    //       this.$forceUpdate()
    //   }else {
    //     this.supplyForm.suppStandard = ''
    //   }
    //   }
      
    changeType(val) {
       if(this.isEditorMode) {
         if(val == 1) {
           if(localStorage.getItem('code')) {
             this.supplyForm.suppStandard = localStorage.getItem('code')
           }else {
             this.getCode()
           }
         }else {
           this.supplyForm.suppStandard = ''
         }
       }else {
         if(val == 1) {
           if(localStorage.getItem('code')) {
             this.supplyForm.suppStandard = localStorage.getItem('code')
           }else {
             this.getCode()
           }
         }else {
           this.supplyForm.suppStandard = ''
         }
       }
    },
    getCode() {
       GetInRandomCode().then(res => {
         if(res.code == 200) {
           localStorage.setItem('code',res.data) 
          //  if(this.supplyForm.suppType == 1) {
            this.supplyForm.suppStandard = localStorage.getItem('code')
            this.$forceUpdate()
          //  }
         }
       })
    },
     watchInput(event, key) {
      this.supplyForm[key] = this.inputReplaceSpecialChar(event)
    },
    exportOption() {
      // if (!this.multipleSelection || !this.multipleSelection.length) {
      //   this.$message.warning('请选择需要导出的商品供应商!');
      //   return;
      // }
      this.loading = true
      const searchData = JSON.parse(JSON.stringify(this.search))
      searchData.startTime = searchData.times[0] ? searchData.times[0] : ''
      searchData.startTime = searchData.times[1] ? searchData.times[1] : ''
      delete searchData.times
      searchData.targetIds = this.multipleSelection.map(item => item.id).join(',')

      this.blobAxiosApi('get', '/cloudApi/goods/goodsSupplier/exportGoodsSupplier', searchData, '商品供应商导出文件.xlsx').finally(() => (this.loading = false))
    },
    switchChange(event, rowData) {
      this.loading = true
      ChangeStoreSupplyStatus({ id: rowData.id })
        .finally(() => (this.loading = false))
        .then(data => {
          if (data.code == 200) {
            this.$message.success((event ? '启用' : '禁用') + '成功!')
            rowData.status = event ? 1 : 0
          } else {
            this.$message.error((event ? '启用' : '禁用') + '失败!')
          }
        })
    },
    handleSelectionChange(selectlist) {
      this.multipleSelection = selectlist
    },
    // 关闭弹窗 - 表单
    cancelSubmit() {
      localStorage.removeItem('code');
      this.isShowerMode = false
      this.isEditorMode = false
      this.isShowDialog = false
      setTimeout(() => {
        this.resetForm()
      }, 300)
    },
    // 确认按钮 - 表单
    confirmSubmit() {
      if (this.isShowerMode) {
        this.isShowDialog = false
        this.isShowerMode = false
        return
      }
      if (!this.validForm()) return
      this.submitLoading = true
      if (!this.isEditorMode) {
        SaveStoreSupply({
          name: this.supplyForm.name,
          suppType: this.supplyForm.suppType,
          // suppCode: this.supplyForm.suppCode,
          suppStandard: this.supplyForm.suppStandard,
        }).finally(() => this.submitLoading = false)
          .then(data => {
            // this.submitLoading = false
            if (data.code == 200) {
              this.$message.success('新建成功!')
              this.isShowDialog = false
              this.getPageDataList()
            } else {
              this.$message.error('新建失败!')
            }
          })
          .catch(error => {
            this.submitLoading = false
          })
      } else {
        UpdateStoreSupply({
          id: this.editSupplyId,
          name: this.supplyForm.name,
          suppType: this.supplyForm.suppType,
          // suppCode: this.supplyForm.suppCode,
          suppStandard: this.supplyForm.suppStandard,
        })
          .then(data => {
            this.submitLoading = false
            if (data.code == 200) {
              this.$message.success('修改成功!')
              this.isShowDialog = false
              this.getPageDataList()
            } else {
              this.$message.error('修改失败!')
            }
          })
          .catch(error => {
            this.submitLoading = false
          })
      }
      localStorage.removeItem('code');
    },
    // 新增供应商
    addSupplyOption() {
      this.resetForm()
      // this.getCode()
      this.isShowerMode = false
      this.isEditorMode = false
      this.isShowDialog = true
    },
    // 查看供应商
    showSupplyOption(data) {
      this.resetForm()
      this.isShowerMode = true
      this.isEditorMode = false
      this.editSupplyId = data.id
      this.isShowDialog = true

      this.renderFormByData(data.id)
    },
    // 编辑供应商
    editSupplyOption(data) {
      this.resetForm()
      this.isShowerMode = false
      this.isEditorMode = true
      this.editSupplyId = data.id
      this.isShowDialog = true

      this.renderFormByData(data.id)
    },
    deleteAllSupplyOption() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message.error('请选择需要删除的供应商!')
        return
      }
      this.deleteSupplyOption(this.multipleSelection.map(item => item.id).join(','))
    },
    // 删除供应商
    deleteSupplyOption(ids) {
      this.$confirm('此操作将删除该供应商, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            // instance.confirmButtonText = '加载中...'
            RemoveStoreSupply({ ids: ids })
              .then(data => {
                instance.confirmButtonLoading = false
                if (data.code == 200) {
                  done()
                  this.$message.success('删除成功!')
                  this.getPageDataList()
                } else {
                  instance.confirmButtonLoading = false
                  instance.confirmButtonText = '确定'
                  this.$message.error('删除失败!')
                }
              })
              .catch(error => {
                instance.confirmButtonLoading = false
              })
          } else {
            done()
          }
        },
      })
    },
    // 获取供应商的信息并且去赋值
    renderFormByData(id) {
      GetStoreSupplyOneItem({ id }).then(data => {
        if (data.code == 200) {
          this.supplyForm.name = data.data.name
          this.supplyForm.suppType = data.data.suppType
          this.supplyForm.suppStandard = data.data.suppStandard
          this.supplyForm.suppCode = data.data.suppCode
        } else {
          this.$message.error('供应商信息获取失败!')
        }
      })
    },
    // 获取数据API
    getPageDataList() {
      this.loading = true
      const searchData = {
        name: this.search.name,
        suppStandard: this.search.suppStandard,
        suppCode: this.search.suppCode,
        startTime: this.search.times && this.search.times[0] ? this.search.times[0] : '',
        endTime: this.search.times && this.search.times[1] ? this.search.times[1] : '',
      }
      GetStoreSupplyListByParams({
        ...searchData,
        pageNum: this.pageIndex,
        pageSize: this.pageSize,
      })
        .finally(() => this.loading = false)
        .then(data => {
          if (data.code == 200) {
            this.pageData = data.data.list
            this.pageCount = data.data.total

            if ((!data.data.list || !data.data.list.length) && this.pageIndex > 1) {
              this.pageIndex = 1
              this.getPageDataList()
            }
          } else {
            this.pageData = []
            this.pageCount = 0
            this.$message.error('加载失败，请重新刷新列表!')
          }
        })
    },
    // 重置
    resetOption() {
      this.search = {
        name: '',
        suppStandard: '',
        suppCode: '',
        times: [],
      }
      this.getPageDataList()
    },
    resetForm() {
      this.supplyForm = {
        name: '', // 名称
        suppType: 0,
        suppStandard: '',
        suppCode: '',
      }
    },

    // 分页操作
    handlePagingChange(event) {
      this.pageIndex = event
      this.getPageDataList()
    },
    handleSizeChange(event) {
      this.pageIndex = 1
      this.pageSize = event
      this.getPageDataList()
    },
    // 表单验证
    validForm() {
      if (!this.supplyForm.name) {
        this.$message.warning('请输入供应商名称!')
        return false
      }
      if (!this.supplyForm.suppStandard) {
        this.$message.warning('请输入供应商编码!')
        return false
      }
      if (!Setting.expression[0].value.test(this.supplyForm.suppStandard)) {
        this.$message.warning('供应商编码只能输入字母和数字!')
        return false
      } else {
        if (this.supplyForm.suppType == '1') {
          if (this.supplyForm.suppStandard.substr(0, 1) == 'C') {
            return true
          } else {
            this.$message.warning('供应商编码开头字母要为C')
            return false
          }
        }
      }
      return true
    },
  },
  created() {
    this.getPageDataList()
  },
}
</script>

<style lang="scss" scoped>
.avator {
  width: 30px;
  height: 30px;
}

::v-deep .el-tree-node__content {
  height: 38px;
}
::v-deep .el-date-editor .el-range-separator {
  width: auto;
}
// ::v-deep .el-input--medium .el-input__inner {
//   text-transform:uppercase;
// }
.width_104 {
  width: 104px;
}
</style>
